package com.mixmall.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mixmall.entity.MaiProductUser;
import com.mixmall.service.IMaiProductUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.List;
@Component
public class CustoUserDetailService implements UserDetailsService {
    @Autowired
    IMaiProductUserService maiProductUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<MaiProductUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(MaiProductUser::getUserName,username)
                .eq(MaiProductUser::getId,1);
        MaiProductUser maiProductUser = maiProductUserService.getOne(queryWrapper);
        if (maiProductUser==null){
            return null;
        }else {
            List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE.admin");
            return new User(maiProductUser.getUserName(),new BCryptPasswordEncoder()
                    .encode(maiProductUser.getPassword()),authorities);
        }
    }
}
